import { ValidationChain, body } from "express-validator";
import { Request, Response, NextFunction } from "express";
import validate from "../index";
import RoleModel from "../../models/role/index";

export const roleNameValidator = (method: any): ValidationChain => method("name").notEmpty().withMessage("角色名不能为空");

class RoleValidator {
  async addRole(req: Request, res: Response, next: NextFunction) {
    const validators = [
      roleNameValidator(body)
        .bail()
        .custom(async value => {
          const user = await RoleModel.findOne({ where: { name: value } });
          if (!user) return true;
          if (user) {
            throw new Error("角色名已经存在");
          }
        })
    ];
    (await validate(validators, req, res)) && next();
  }
  async deleteRole(req: Request, res: Response, next: NextFunction) {
    const validators = [
      body("id")
        .notEmpty()
        .withMessage("id不能为空")
        .bail()
        .custom(async value => {
          const user = await RoleModel.findOne({ where: { id: value } });
          //   console.log(user.users);
          if (!user) throw new Error("角色不存在");
          if (user && user.users) throw new Error("角色下存在用户");
          return true;
        })
    ];
    (await validate(validators, req, res)) && next();
  }
}

export default RoleValidator;
